import traceback
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow
from threading import Thread
from jsjj.gui.qt5.main.gui import *
from jsjj.util.dbUtil import *
import datetime
import socket
import pandas as pd
from jsjj.util.emailUtil import *
import os
import jsjj.mouseKeyboard.taobao.sycm.T_SYCM_Scdp_d_m as t_sycm_scdp_d_m
import jsjj.mouseKeyboard.taobao.sycm.T_SYCM_Scph_goods_w_m as t_sycm_scph_goods_w_m
import jsjj.mouseKeyboard.taobao.sycm.T_SYCM_Scph_dianpu_w_m as t_sycm_scph_dianpu_w_m

import jsjj.mouseKeyboard.pdd.dianba.P_DB_Hyzl as p_db_hyzl
import jsjj.mouseKeyboard.pdd.dianba.P_DB_Rxsp7 as p_db_rxsp7
import jsjj.mouseKeyboard.pdd.dianba.P_DB_Rxsp30 as p_db_rxsp30

import jsjj.mouseKeyboard.jd.ziying.J_ZY_Hygk_d as j_zy_hygk_d
import jsjj.mouseKeyboard.jd.ziying.J_ZY_Dpbd_w_m as j_zy_dpbd_w_m
import jsjj.mouseKeyboard.jd.ziying.J_ZY_Spbd_m as j_zy_spbd_m

import jsjj.mouseKeyboard.jd.pop.J_POP_Hydp as j_pop_hydp
import jsjj.mouseKeyboard.jd.pop.J_POP_Jybd as j_pop_jybd
import jsjj.mouseKeyboard.jd.pop.J_POP_Top100 as j_pop_top100

from jsjj.etl.pdd.MergePddFullOperation import *
# 商家后台
import jsjj.mouseKeyboard.pdd.sjht.P_HT_Splb_OnlineGoods_d as p_ht_splb_onlinegoods_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_Dplhy_d as p_ht_dplhy_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_Shsj_d as p_ht_shsj_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_Spgk_d as p_ht_spgk_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_Spmx_d as p_ht_spmx_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_Llkb_d as p_ht_llkb_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_DuoDuokefu_d as p_ht_duoduokefu_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_DuoDuoSearch_d as p_ht_duoduosearch_d
import jsjj.mouseKeyboard.pdd.sjht.P_HT_DuoDuoSearch_d as p_ht_duoduosearch_d

def suggestion():
    # 连接database
    machineNo = 0
    engine, conn = getConn()
    # 解决可能出现的超时问题
    conn.connection.connection.ping(reconnect=True)
    sqlAll = "SELECT 机器编号 FROM 平台_物理机虚拟机 "
    dfAll = pd.read_sql(sql=sqlAll, con=engine)
    sqlLoop = "SELECT 机器编号 FROM 平台_物理机虚拟机 where 机器名称='" + socket.gethostname() + "' "
    dfLoop = pd.read_sql(sql=sqlLoop, con=engine)
    for index, row in dfLoop.iterrows():
        machineNo = row['机器编号']

    taskno = (int(machineNo) + datetime.datetime.now().weekday()) % dfAll.shape[0]
    return taskno


def getSuggestionText():
    taskno = suggestion()
    suggestionText = ''
    url = ''
    if taskno == 0:
        suggestionText = '京东POP'
        url = 'https://sz.jd.com/sz/view/dealAnalysis/dealFeatures.html'
    elif taskno == 1:
        suggestionText = '京东自营'
        url = 'https://ppzh.jd.com/brand/industry/industryTrend.html'
    elif taskno == 2:
        suggestionText = '电霸'
        url = 'http://www.dianba6.com/'
    elif taskno == 3:
        suggestionText = '拼多多商家后台'
        url = 'https://mms.pinduoduo.com/'
    elif taskno == 4:
        suggestionText = '生意参谋'
        url = 'http://sycm.taobao.com/portal/home.htm'
    else:
        pass
    return '建议运行:' + suggestionText + ',' + url


class mywindow(QtWidgets.QMainWindow, Ui_MainWindow):
    # 全局变量
    engine, conn = getConn()

    def __init__(self):
        super(mywindow, self).__init__()
        self.setupUi(self)
        # mywindow.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        # 下拉框的初始化
        self.comboBox_J_POP_Hydp.clear()
        # self.comboBox_J_POP_Hydp.addItem('请选择')
        # for k, v in combobox.runMode.items():
        #     self.comboBox_J_POP_Hydp.addItem(v, k)  # 键、值反转
        # self.comboBox_J_POP_Hydp.setItemText(0,"日模式")
        # self.comboBox_J_POP_Hydp.setItemText(1, "周模式")
        # self.comboBox_J_POP_Hydp.setItemText(2, "月模式")

    # 定义自己的槽函数
    def hello(self):
        self.textEdit.setText("hello world,trigger")

    def P_DB_Hyzl(self):
        print("P_DB_Hyzl")
        self.engine.execute("update 平台_类目表 set dianba_hyzl='0' where channel='拼多多' ")

    def P_DB_Rxsp7(self):
        print("P_DB_Rxsp7")
        self.engine.execute("update 平台_类目表 set dianba_rxsp='0' where channel='拼多多' ")

    def P_DB_Rxsp30(self):
        print("P_DB_Rxsp30")
        self.engine.execute("update 平台_类目表 set dianba_rxsp30='0' where channel='拼多多' ")

    def T_SYCM_Scdp_d_m(self):
        self.engine.execute("update 平台_类目表 set taobao_sycm_scdp='0' where channel='淘宝' ")

    def T_SYCM_Scph_dianpu_w_m(self):
        self.engine.execute("update 平台_类目表 set taobao_sycm_scph_dianpu='0' where channel='淘宝' ")

    def T_SYCM_Scph_goods_w_m(self):
        self.engine.execute("update 平台_类目表 set taobao_sycm_scph_goods='0' where channel='淘宝' ")

    # 类的调用
    def T_SYCM_Scdp_d_m_2(self):
        # 淘宝_生意参谋_市场_市场大盘
        t_sycm_scdp_d_m.runMode = self.comboBox_T_SYCM_Scdp_d_m.currentText()
        t = Thread(target=t_sycm_scdp_d_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def T_SYCM_Scph_goods_w_m_2(self):
        # 淘宝_生意参谋_市场_市场排行_商品TOP100
        t_sycm_scph_goods_w_m.runMode = self.comboBox_T_SYCM_Scph_goods_w_m.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=t_sycm_scph_goods_w_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def T_SYCM_Scph_dianpu_w_m_2(self):
        # 淘宝_生意参谋_市场_市场排行_店铺
        t_sycm_scph_dianpu_w_m.runMode = self.comboBox_T_SYCM_Scph_dianpu_w_m.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=t_sycm_scph_dianpu_w_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def P_DB_Rxsp7_Catch(self):
        # 拼多多_电霸_近7天热销商品
        p_db_rxsp7.runMode = self.comboBox_P_DB_Rxsp7.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=p_db_rxsp7.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def P_DB_Rxsp30_Catch(self):
        # 拼多多_电霸_近7天热销商品
        p_db_rxsp30.runMode = self.comboBox_P_DB_Rxsp30.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=p_db_rxsp30.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def P_DB_Hyzl_Catch(self):
        # 拼多多_电霸_行业总览
        p_db_hyzl.runMode = self.comboBox_P_DB_Hyzl.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=p_db_hyzl.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def J_ZY_CatchAll(self):
        # 京东_纯自营_行业_行业概况
        j_zy_hygk_d.runMode = self.comboBox_J_ZY_Hygk_d.currentText()
        # 启动一个线程来检查文件是否生成了
        t_zy1 = Thread(target=j_zy_hygk_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t_zy1.start()
        t_zy1.join()

        # 京东_纯自营_行业_店铺榜单
        j_zy_dpbd_w_m.runMode = self.comboBox_J_ZY_Dpbd_w_m.currentText()
        # 启动一个线程来检查文件是否生成了
        t_zy2 = Thread(target=j_zy_dpbd_w_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t_zy2.start()
        t_zy2.join()

        # 京东_纯自营_行业_商品榜单
        j_zy_spbd_m.runMode = self.comboBox_J_ZY_Spbd_m.currentText()
        # 启动一个线程来检查文件是否生成了
        t_zy3 = Thread(target=j_zy_spbd_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t_zy3.start()
        t_zy3.join()

    def J_ZY_Hygk_d(self):
        # 京东_纯自营_行业_行业概况
        j_zy_hygk_d.runMode = self.comboBox_J_ZY_Hygk_d.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=j_zy_hygk_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def J_ZY_Dpbd_w_m(self):
        # 京东_纯自营_行业_店铺榜单
        j_zy_dpbd_w_m.runMode = self.comboBox_J_ZY_Dpbd_w_m.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=j_zy_dpbd_w_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def J_ZY_Spbd_m(self):
        # 京东_纯自营_行业_商品榜单
        j_zy_spbd_m.runMode = self.comboBox_J_ZY_Spbd_m.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=j_zy_spbd_m.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def J_POP_CatchALL(self):
        # 京东_POP_行业大盘走势
        j_pop_hydp.runMode = self.comboBox_J_POP_Hydp.currentText()
        # 启动一个线程来检查文件是否生成了
        tPOP1 = Thread(target=j_pop_hydp.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        tPOP1.start()
        tPOP1.join()

        # 京东_POP_行业大盘_商家榜单_交易榜单
        j_pop_jybd.runMode = self.comboBox_J_POP_Jybd.currentText()
        # 启动一个线程来检查文件是否生成了
        tPOP2 = Thread(target=j_pop_jybd.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        tPOP2.start()
        tPOP2.join()

        # 京东_POP_行业大盘_商品榜单_交易榜单TOP100
        j_pop_top100.runMode = self.comboBox_J_POP_Top100.currentText()
        # 启动一个线程来检查文件是否生成了
        tPOP3 = Thread(target=j_pop_top100.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        tPOP3.start()
        tPOP3.join()


    def J_POP_Hydp(self):
        # 京东_POP_行业大盘走势
        j_pop_hydp.runMode = self.comboBox_J_POP_Hydp.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=j_pop_hydp.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def J_POP_Jybd(self):
        # 京东_POP_行业大盘_商家榜单_交易榜单
        j_pop_jybd.runMode = self.comboBox_J_POP_Jybd.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=j_pop_jybd.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def J_POP_Top100(self):
        # 京东_POP_行业大盘_商品榜单_交易榜单TOP100
        j_pop_top100.runMode = self.comboBox_J_POP_Top100.currentText()
        # 启动一个线程来检查文件是否生成了
        t = Thread(target=j_pop_top100.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
        t.start()

    def Sjht_everyday(self):
        if self.checkBox_p_ht_llkb_d.isChecked():
            # 拼多多_商家后台_流量数据_流量看板    p_ht_llkb_d
            p_ht_llkb_d.runMode = self.comboBox_sjht_everyday.currentText()
            tA = Thread(target=p_ht_llkb_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            tA.start()
            tA.join()  #

        if self.checkBox_p_ht_duoduokefu_d.isChecked():
            # duoduo    p_ht_duoduokefu_d
            p_ht_duoduokefu_d.runMode = self.comboBox_sjht_everyday.currentText()
            tB = Thread(target=p_ht_duoduokefu_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            tB.start()
            tB.join()  #

        if self.checkBox_p_duoduo_search.isChecked():
            # 多多搜索    p_ht_duoduosearch_d
            p_ht_duoduosearch_d.runMode = self.comboBox_sjht_everyday.currentText()
            tC = Thread(target=p_ht_duoduosearch_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            tC.start()
            tC.join()  #

        if self.checkBox_p_ht_spgk.isChecked():
            # 拼多多_商家后台_商品概况    p_ht_spgk_d
            print('start1:' + datetime.datetime.now().strftime('%m-%d %H:%M:%S'))
            p_ht_spgk_d.runMode = self.comboBox_sjht_everyday.currentText()
            t1 = Thread(target=p_ht_spgk_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            t1.start()
            t1.join()  #
            print('over1:' + datetime.datetime.now().strftime('%m-%d %H:%M:%S'))

        if self.checkBox_p_ht_spmx.isChecked():
            # 拼多多_商家后台_商品明细                         p_ht_spmx_d
            print('start2:' + datetime.datetime.now().strftime('%m-%d %H:%M:%S'))
            p_ht_spmx_d.runMode = self.comboBox_sjht_everyday.currentText()
            t2 = Thread(target=p_ht_spmx_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            t2.start()
            t2.join()  #
            print('over2:' + datetime.datetime.now().strftime('%m-%d %H:%M:%S'))
        if self.checkBox_p_ht_splb_onlinegoods.isChecked():
            # 拼多多_商家后台_商品列表_线上商品                 p_ht_splb_onlinegoods_d
            p_ht_splb_onlinegoods_d.runMode = self.comboBox_sjht_everyday.currentText()
            t3 = Thread(target=p_ht_splb_onlinegoods_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            t3.start()
            t3.join()  #
        if self.checkBox_p_ht_dplhy.isChecked():
            # 拼多多_商家后台_服务数据_店铺领航员                p_ht_dplhy_d
            p_ht_dplhy_d.runMode = self.comboBox_sjht_everyday.currentText()
            t4 = Thread(target=p_ht_dplhy_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            t4.start()
            t4.join()  #
        if self.checkBox_p_ht_shsj.isChecked():
            # 拼多多_商家后台_服务数据_评价数据_店铺dsr          p_ht_shsj_d
            p_ht_shsj_d.runMode = self.comboBox_sjht_everyday.currentText()
            t5 = Thread(target=p_ht_shsj_d.executeCatchWeb, args=(self.engine, self.conn), daemon=True)
            t5.start()
            t5.join()  #
        # 拼多多_商家后台_服务数据_评价数据_近30天商品评价    p_ht_shsj_d
        # 拼多多_商家后台_服务数据_售后数据                 p_ht_shsj_d
        # 所有过程执行完成后，会自动执行生成中间表的过程
        generatePddOperationFull(self.engine, self.conn)
        sendAlert('●拼多多每日进程完成●主程序', '' + os.path.split(__file__)[-1], self.engine, self.conn)

def jobs():
    # 每天要运行的自动任务
    #replace into 平台_任务_机器_实例表_h(select * from 平台_任务_机器_实例表);
    #replace into 平台_任务异常信息_h(select * from 平台_任务异常信息);
    pass

def moveInfomationtoHistory(engine):
    #replace into 平台_任务_机器_实例表_h(select * from 平台_任务_机器_实例表);
    #delete from 平台_任务_机器_实例表;
    #replace into 平台_任务异常信息_h(select * from 平台_任务异常信息);
    #delete from 平台_任务异常信息;
    pass

def runSqlEveryDay(engine):
    # 这里有特殊的逻辑，不同账号，可能有相同的类目，同一天的数据，是一模一样的，因此我们需要去除重复数据的
    # =====================================================================================================
    # 拼多多_商家后台_商品概况
    sql = 'delete from a                                                              '
    sql += '    using 平台_任务_机器_实例表 as a, 平台_任务_机器_实例表 as b   '
    sql += '    where (a.id < b.id)                                                    '
    sql += '    and (a.任务表名称 = b.任务表名称 and a.当前运行机器名=b.当前运行机器名 and a.运行机器描述=b.运行机器描述 and a.运行模式=b.运行模式 and a.执行账号=b.执行账号)     '
    engine.execute(sql)

    # 合并部分数据
    sql = ' update 财务_拼多多周度订单明细 a, 平台_拼多多_简尚_sku_spu b set a.SPU=b.辅助码,a.尺寸=b.商品尺寸,a.颜色=b.颜色 '
    sql += ' where  a.条形码=b.商品条码 '
    # 并不一定是天天
    # engine.execute(sql)


if __name__ == '__main__':
    suggestionText = getSuggestionText()
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = mywindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    # 业务代码
    ui.textEdit.setText(suggestionText)
    runSqlEveryDay(ui.engine)
    moveInfomationtoHistory(ui.engine)
    try:
        # 绑定事件
        # 更新断点续传标志
        ui.pushButton_P_DB_Hyzl.clicked.connect(ui.P_DB_Hyzl)
        ui.pushButton_P_DB_Rxsp7.clicked.connect(ui.P_DB_Rxsp7)
        ui.pushButton_P_DB_Rxsp30.clicked.connect(ui.P_DB_Rxsp30)

        # 开始抓取
        ui.pushButton_P_DB_Rxsp7_Catch.clicked.connect(ui.P_DB_Rxsp7_Catch)
        ui.pushButton_P_DB_Rxsp30_Catch.clicked.connect(ui.P_DB_Rxsp30_Catch)
        ui.pushButton_P_DB_Hyzl_Catch.clicked.connect(ui.P_DB_Hyzl_Catch)

        # 开始抓取
        ui.pushButton_J_ZY_Hygk_d.clicked.connect(ui.J_ZY_Hygk_d)
        ui.pushButton_J_ZY_Dpbd_w_m.clicked.connect(ui.J_ZY_Dpbd_w_m)
        ui.pushButton_J_ZY_Spbd_m.clicked.connect(ui.J_ZY_Spbd_m)
        ui.pushButton_ZY_CatchALL.clicked.connect(ui.J_ZY_CatchAll)  # 同时运行

        # 开始抓取
        ui.pushButton_J_POP_Hydp.clicked.connect(ui.J_POP_Hydp)
        ui.pushButton_J_POP_Jybd.clicked.connect(ui.J_POP_Jybd)
        ui.pushButton_J_POP_Top100.clicked.connect(ui.J_POP_Top100)
        ui.pushButton_POP_CatchALL.clicked.connect(ui.J_POP_CatchALL)  # 同时运行

        ui.pushButton_T_SYCM_Scdp_d_m.clicked.connect(ui.T_SYCM_Scdp_d_m)
        ui.pushButton_T_SYCM_Scph_dianpu_w_m.clicked.connect(ui.T_SYCM_Scph_dianpu_w_m)
        ui.pushButton_T_SYCM_Scph_goods_w_m.clicked.connect(ui.T_SYCM_Scph_goods_w_m)

        # 类的调用
        ui.pushButton_T_SYCM_Scdp_d_m_2.clicked.connect(ui.T_SYCM_Scdp_d_m_2)
        ui.pushButton_T_SYCM_Scph_goods_w_m_2.clicked.connect(ui.T_SYCM_Scph_goods_w_m_2)
        ui.pushButton_T_SYCM_Scph_dianpu_w_m_2.clicked.connect(ui.T_SYCM_Scph_dianpu_w_m_2)

        # 每日运行的商家后台
        ui.pushButton_sjht_everyday.clicked.connect(ui.Sjht_everyday)
    except Exception as e:
        traceback.print_exc()
        sendAlert('【异常中断】主程序', '异常:' + str(e) + '|报错文件:' + os.path.split(__file__)[-1], ui.engine, ui.conn)

    sys.exit(app.exec_())
